<html>
<head>
<title>Social Media Monitoring : Popup</title>

<link rel="stylesheet" href="css/content.css" type="text/css" media="all" />
<script type="text/javascript" src="lib/i18n.js"></script>
<script type="text/javascript" src="probe_manager.js"></script>
<script type="text/javascript" src="probe.js"></script>
<script type="text/javascript" src="lib/3rdparty/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="lib/3rdparty/jquery.effects.core.min.js"></script>
<script type="text/javascript" src="lib/3rdparty/jquery.tooltip.min.js"></script>

<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=ABQIAAAATfHumDbW3OmRByfquHd3SRTRERdeAiwZ9EeJWta3L_JZVS0bOBRQeZgr4K0xyVKzUdnnuFl8X9PX0w&sensor=false"></script>
<script type="text/javascript" src="lib/geo_search.js"></script>


<script type="text/javascript"><!--
var probeManager = chrome.extension.getBackgroundPage().getProbeManager();
var probesList;
var currentProbe;
var currentProbeDiv;
var currentSelectedService = "twitter";
var currentLocation = undefined;

var map, probes, template, serviceIcon, inputTag, spanTag, spanLocation, inputAvgWeek, inputAvgDay, btnOptions, btnRefresh, btnSave;

var port = chrome.extension.connect({name: "social-media-monitoring"});

/*
 * i18n
 */
var strSearch = chrome.i18n.getMessage('search_location');
var strLocationSet = chrome.i18n.getMessage('button_set');
var strLocationEnable = chrome.i18n.getMessage('button_enable');

/*
 * TODO:  Automated location detection turned off for now, because of:
 *      - crash on windows 7 with chrome 5.0.342.3 
 *      - Linux (5.0.347.0 (40857) Ubuntu + Suse works) but just iploction because even with --enable-geolocation no html5 geolocation detection...
 *      - Mac?
*/
//port.postMessage({requestGeolocation:'true'});

port.onMessage.addListener(function(msg) {
	  if (msg.update) {
		  probeObj = msg.update;
		  console.log('onMessage[update]:' + probeObj);

		/*
		 * get right element from probe list
		 */
		  var probeHTMLObj = $('#f_' + probeObj.id);

			 if (probeHTMLObj){

				 //$(probeHTMLObj).addClass('warn');
				 $(probeHTMLObj).removeClass('loader');
				 
				 $(' > span#tag',probeHTMLObj).html($(' > input#tag_input',probeHTMLObj).val());
				 
				 $(' > span#tag',probeHTMLObj).removeClass('hd');
				 $(' > input#tag_input',probeHTMLObj).addClass('hd');
				 $(' > span.avgWeek',probeHTMLObj).html(probeObj.shortTermTweetsPerMin);
				 $(' > span.avgDay',probeHTMLObj).html(probeObj.longTermTweetsPerMin);
				 $(' > span#btnOptions',probeHTMLObj).removeClass('hd');
				 $(' > span#btnSave',probeHTMLObj).addClass('hd');
				 
				 
				 $(' > span#btnRefresh',probeHTMLObj).removeClass('hd');
				 $(' > span#btnRefresh',probeHTMLObj).removeClass('reloading');
				 $(' > span#btnRefresh',probeHTMLObj).addClass('idle');
				 
				 
				 if(probeObj.latitude == undefined){
					 $(' > span#btnOptions',probeHTMLObj).addClass('disabled');
					 $(' > span#probe_geo',probeHTMLObj).addClass('hd');
				 }
				 
				 $('#show-button').attr("disabled", "");
				 setAddButton();
				 
			 }

	  }
	  if (msg.alert) {
		  probeObj = msg.alert;
		  console.log('onMessage[alert]:' + probeObj);
		  
		  var probeHTMLObj = $('#f_' + probeObj.id);

		  if (probeHTMLObj){
		  	$(probeHTMLObj).addClass('marker');
		  	$(probeHTMLObj).removeClass('loader');
		  	$(' > span#btnRefresh',probeHTMLObj).addClass('idle');
			if(chrome.extension.getBackgroundPage().settings.hideProbeLabels == true || chrome.extension.getBackgroundPage().settings.hideProbeLabels == 'true' ){
				$('> .avgWeek', probeHTMLObj).css('display','inline');
				$('> .avgDay', probeHTMLObj).css('display','inline');	
			}	
		  }
	  }
	  if (msg.onLocationResult) {
		  currentLocation = msg.onLocationResult;
	  }  
});

$(document).ready(function() {
	/*
	 * i18n
	 */
	$('#location').val(strSearch);
	 
	$("#btnAdd").click(function() {

		/*
		 * check if probe is filled
		 */
		var ignore = false;
		$('#f').each(function(i){

			 var tagObj = $(' > input#tag_input.tag',this);
			 var probeValue = tagObj.val();
			 console.log('probeValue:' + probeValue);
			 if (!probeValue){
				 $(tagObj).animate({backgroundColor: "#f4aeae"}, "fast").animate({backgroundColor: "#fffff"}, "fast");
				 ignore = true;
				 return false;
			 }
			 
			 if($(tagObj).is(':visible')){
				 $(tagObj).animate({backgroundColor: "#f4aeae"}, "fast").animate({backgroundColor: "#fffff"}, "fast");
				 ignore = true;
				 return false;
			 }

			 
			 
		});

		if(!ignore && !$(this).is('.disabled')){
			currentSelectedService = "twitter";
			addProbeHTML();
			addButtonListeners();
		}  
	});

	/*
	 * set tooltips
	 */
/*
	 $(".tKeywords").tooltip({
		bodyHandler: function() {
			return chrome.i18n.getMessage('tooltip_tkeywords');
		},
		showURL: false
	});
*/	
	$(".ltTpM").tooltip({
		bodyHandler: function() {
			return chrome.i18n.getMessage('tooltip_ltTpM');
		},
		showURL: false
	});

	$(".cTpM").tooltip({
		bodyHandler: function() {
			return chrome.i18n.getMessage('tooltip_cTpM');
		},
		showURL: false
	});
	
});

function openResults() {

	var probes = probeManager.loadProbes();
	
	if ($('#open_results').val() == 'open_in_new_window') {
		chrome.windows.create({url: buildProbeQuery(probes[0])});
		chrome.windows.getLastFocused(function (window) {

			var count = 0;
			for (var j in probes) {
				count++;
				if(count == 1){
					continue;
				}
					chrome.tabs.create({url: buildProbeQuery(probes[j]), windowId: window.windowId});
			}
		
		});
	} else {	
	
		for (var i in probes) {
			chrome.tabs.create({url: buildProbeQuery(probes[i])});
		}
	
	}
	
}


--></script>

<style type="text/css">
  @import url("http://www.google.com/uds/css/gsearch.css");
  @import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
</head>
<body onload="setTimeout(init,0);" onunload="GUnload();" class="popup">

<div id="options">

<a href="#" id="back" onclick="back();"><script type="text/javascript">_writeMessage('popup_goback');</script></a>

<div id="geolocform">
	<form action="javascript:void(0);" onsubmit="showAddress(this.location.value); return false;"> 
   	  <input id="location" type="text" name="location" value="strSearch" onfocus="if(this.value==strSearch){this.value='';}">
   	  <select id="distance" name="distance"><option value="10">10</option><option value="20">20</option><option value="30">30</option><option value="40">40</option><option value="50">50</option><option value="60">60</option><option value="70">70</option><option value="80">80</option><option value="90">90</option><option value="100">100</option><option value="200">200</option></select>
   	  <select id="unit" name="unit"><option value="km"><script type="text/javascript">_writeMessage('kilometres');</script></option>
   	  <!--  <option value="mi">miles</option>-->
   	  </select>
   	  <br>
	</form>
</div>
   	
<div id="map_canvas"></div>

<span id="lat"></span> 
<span id="lng"></span>
<button type="button" id="enable_location"><script type="text/javascript">_writeMessage('button_enable');</script></button>
<button type="button" id="disable_location"><script type="text/javascript">_writeMessage('button_disable');</script></button>
<span id="save_status"><script type="text/javascript">_writeMessage('status_saved');</script></span>

</div>
<script type="text/javascript"><!--
function init() {

	var probes = probeManager.loadProbes();

	/*
	 * initialize template
	 */
	probesList = document.getElementById('probes');
	template = xpath('//ol[@id="template"]/li', document);
	serviceIcon  = xpath('//span[@id="iconService"]', template);
	spanTag  = xpath('//span[@id="tag"]', template);
	spanLocation  = xpath('//span[@id="probe_geo"]', template);
	
	inputTag = xpath('//input[@id="tag_input"]', template);
	inputAvgWeek = xpath('//span[@class="avgWeek"]', template);
	inputAvgDay	 = xpath('//span[@class="avgDay"]', template);
	btnOptions	 = xpath('//span[@id="btnOptions"]', template);
	btnRefresh 	 = xpath('//span[@id="btnRefresh"]', template);
	btnSave 	 = xpath('//span[@id="btnSave"]', template);

	if(probes){
		$('#show-button').attr("disabled", "");
		for (var i in probes) {
			addProbeHTML(probes[i]);
		}
		setAddButton();
		addButtonListeners();
	}

	/* hide show labels */
	
	console.log(chrome.extension.getBackgroundPage().settings.hideProbeLabels);
	if(chrome.extension.getBackgroundPage().settings.hideProbeLabels == true || chrome.extension.getBackgroundPage().settings.hideProbeLabels == 'true' ){
		$('.title').css('display','none');
		$('.avgWeek').css('display','none');
		$('.avgDay').css('display','none');	
	}
	

	
	chrome.extension.getBackgroundPage().resetAlerts();
}

function setAddButton(){
	console.log('setAddButton:' + chrome.extension.getBackgroundPage().maxProbesLimit + ' <= ' + probeManager.countProbes());
	
	if(chrome.extension.getBackgroundPage().maxProbesLimit <= probeManager.countProbes()){
		$('#btnAdd').addClass("disabled");
		console.log('	disable');
	}else{
		console.log('	enable');
		$('#btnAdd').removeClass("disabled");
	}
}
function addButtonListeners(){
	$("span#btnRemove").click(function() {
		/*
		 * get selected probe id
		 */		
		var probeDiv = $(this).parent('.probe');
		var strDivId = probeDiv.attr('id');
		strDivId = strDivId.substring(2);

		/*
		 * remove
		 */
		probeManager.removeProbeById(strDivId);
		setAddButton();
		
		/*
		 * remove from HTML
		 */
	    probeDiv.slideUp("fast",function(){
		        
				probeDiv.remove();
	    });

		if(probeManager.countProbes() == 0){
	    	chrome.extension.getBackgroundPage().showNoActiveProbes()
	    	$('#show-button').attr("disabled", "true");
		}

		/*
		 * Update probes
		 */

/*		
		chrome.extension.getBackgroundPage().updateProbes(function(count) {
			//dummy function
			console.log('updateProbes.callback:' + count);
		  });
*/			

	});
	/*
	 * show options
	 */
	$("span#btnOptions").click(function() {
		/*
		 * get selected probe id
		 */		
		currentProbeDiv = $(this).parent('.probe');
		var strDivId = currentProbeDiv.attr('id');
		strDivId = strDivId.substring(2);

		currentProbe = probeManager.getProbeById(strDivId);

		$("#save_status").css('display','none');

		
		if(currentProbe.latitude != undefined){
			$("#enable_location").css('display','inline');
			$("#enable_location").html(strLocationSet);
			
			$("#disable_location").css('display','inline');
			$("#location").val(currentProbe.locationAddress);

		}else{
			$("#enable_location").html(strLocationEnable);
			$("#enable_location").css('display','inline');
			$("#disable_location").css('display','none');
			$('#location').val(strSearch);
		}
		
		if (currentProbe.latitude != undefined && currentProbe.longitude != undefined)
			initMapSearch(currentProbe.latitude, currentProbe.longitude, function(adress){
				console.log('adress:' + adress);
				 onLocationChanged(adress);
			 });
		else if(currentLocation !== undefined) {
			minitMapSearch(currentLocation.latitude, currentLocation.longitude);
		}
		else {
			/*
			 * preset with default location
			 */
			if (chrome.extension.getBackgroundPage().settings.latitude != undefined && chrome.extension.getBackgroundPage().settings.latitude != 'undefined'){
				console.log(chrome.extension.getBackgroundPage().settings.latitude);
				initMapSearch(chrome.extension.getBackgroundPage().settings.latitude,chrome.extension.getBackgroundPage().settings.longitude, function(adress){
					console.log('adress:' + adress);
					onLocationChanged(adress);
				 });
			}else{
				initMapSearch(37.4328, -122.077, function(adress){
					console.log('adress:' + adress);
					onLocationChanged(adress);
				 }); //hello google ;)
			}
		}

		
		$("#distance").val(currentProbe.radius);
		
		$("div#options").slideDown("fast");
	});

	/*
	 * refresh results
	 */
	$("span#btnRefresh").mousedown(function() {
		/*
		 * get selected probe id
		 */		
		currentProbeDiv = $(this).parent('.probe');
		var strDivId = currentProbeDiv.attr('id');
		strDivId = strDivId.substring(2);
		//$(currentProbeDiv).addClass('loader');
		
		$(' > span#btnRefresh',currentProbeDiv).addClass('reloading');
		
		currentProbe = probeManager.getProbeById(strDivId);

		port.postMessage({probeTagChanged: currentProbe});
	});

	$("span#btnSave").click(function() {

		if (!$(this).is('.disable')){
			save();
		}
		
	});
	
	

	$("span#iconService").click(function() {
		/*
		 * get selected probe id
		 */		
		currentProbeDiv = $(this).parent('.probe');
		var strDivId = currentProbeDiv.attr('id');
		strDivId = strDivId.substring(2);

		var probeObj = probeManager.getProbeById(strDivId);
		var radius = ""; 
		if (probeObj.radius != undefined){
			radius = probeObj.radius;
		}

		window.open(buildProbeQuery(probeObj)); 
		return false;
		
	});
	
	$("#enable_location").click(function() {

		/*
		 * reload probe (if it was in between changed)
		 */
		currentProbe = probeManager.getProbeById(currentProbe.id);

		currentProbe.latitude = $("#lat").html();
		currentProbe.longitude  = $("#lng").html();
		currentProbe.radius  = $("#distance").val();
		currentProbe.locationAddress = $("#location").val();
		
		probeManager.setProbe(currentProbe);

		$(' > span#probe_geo',currentProbeDiv).html($("#location").val());
		$(' > span#probe_geo',currentProbeDiv).removeClass('hd');
		
		$(' > span#btnOptions',currentProbeDiv).removeClass('disabled');
		//$(currentProbeDiv).addClass('loader');
		$(' > span#btnRefresh',currentProbeDiv).addClass('reloading');
		
		$('#save_status').fadeIn('fast');
		$('#save_status').fadeOut(3000);
		$("div#options").css('display','none');
		$(this).css('display','none');
		$("#disable_location").css('display','none');		

		port.postMessage({probeTagChanged: currentProbe});

		
		
	});
	
	$("#disable_location").click(function() {

		/*
		 * reload probe (if it was in between changed)
		 */
		currentProbe = probeManager.getProbeById(currentProbe.id);

		currentProbe.latitude = undefined;
		currentProbe.longitude  = undefined;
		currentProbe.radius  = undefined;
		currentProbe.locationAddress = undefined;
		probeManager.setProbe(currentProbe);

		//$(currentProbeDiv).addClass('loader');
		$(' > span#btnRefresh',currentProbeDiv).addClass('reloading');
		$(' > span#btnOptions',currentProbeDiv).addClass('disabled');	
		$(' > span#probe_geo',currentProbeDiv).html('');
		$(' > span#probe_geo',currentProbeDiv).addClass('hd');
				
		$('#save_status').fadeIn('fast');
		$('#save_status').fadeOut(3000);
		$("div#options").css('display','none');
		$(this).css('display','none');
		$("#enable_location").css('display','none');
		
		

		port.postMessage({probeTagChanged: currentProbe});		

	});
	
	

    $(".probe").click(function () {
    	       $(".probe").removeClass("selected");
    	       $(this).addClass("selected");
    	      }
    ).mouseover( function () {
		 //$(' > #btnRemove',this).removeClass("hd");
		 $(this).addClass("selected");

			if(chrome.extension.getBackgroundPage().settings.hideProbeLabels == true || chrome.extension.getBackgroundPage().settings.hideProbeLabels == 'true' ){
				$('> .avgWeek', this).css('display','inline');
				$('> .avgDay', this).css('display','inline');	
			}	 
		    
		}
	).mouseout( function () {
		//$(' > #btnRemove',this).addClass("hd");
	    $(this).removeClass("selected");

		if(chrome.extension.getBackgroundPage().settings.hideProbeLabels == true || chrome.extension.getBackgroundPage().settings.hideProbeLabels == 'true' ){
			$('> .avgWeek', this).css('display','none');
			$('> .avgDay', this).css('display','none');	
		}	 	    
	    	 
	    }
	);

    $("input#tag_input").keypress(function (e) {  
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			save();
        	return false;  
        } else {
            return true;  
        }  
    }).keyup(function (e) {
        var parent = $(this).parent();
    	if($(this).val()){
    		 $("> span#btnSave",parent).removeClass("disabled");
        }else{
        	$(">span#btnSave",parent).addClass("disabled");
        }

   });
	
    
}

function onLocationChanged(adress){
	console.log('onLocationChanged...' + adress);
	$("#location").val(adress);
}

function addProbeHTML(probeObj){

	if(probeObj){		

		spanTag.innerHTML = probeObj.query;
		
		spanLocation.innerHTML = probeObj.locationAddress;

		serviceIcon.setAttribute('class','service_' + probeObj.serviceId);
		
		spanTag.setAttribute('class','span_tag');
		spanLocation.setAttribute('class','span_geo');
			
		inputTag.setAttribute('class','tag hd');
		
		inputTag.setAttribute('value',probeObj.query);
		inputAvgWeek.innerHTML = probeObj.shortTermTweetsPerMin;
		inputAvgDay.innerHTML = probeObj.longTermTweetsPerMin;

		if(probeObj.latitude == undefined){
			btnOptions.setAttribute('class','disabled');
			spanLocation.setAttribute('class','hd');
		}else{
			btnOptions.setAttribute('class','');
			spanLocation.setAttribute('class','');
		}
		btnSave.setAttribute('class','hd');

		// copy node and update
		item = template.cloneNode(true);	  
		item.setAttribute('id','f_' + probeObj.id);
		item.setAttribute('class','probe');

		/*
		 * mark probe if in marker array
		 */
		if (chrome.extension.getBackgroundPage().ifMarkerSet(probeObj.id)){
			item.setAttribute('class','probe marker');
		}

		probesList.appendChild(item);
		
	}else{

		serviceIcon.setAttribute('class','service_' + currentSelectedService);
		
		spanTag.setAttribute('class','span_tag hd');
		spanTag.innerHTML = '';		

		spanLocation.setAttribute('class','hd');
		spanLocation.innerHTML = '';		
		
		inputTag.setAttribute('class','tag');
			
		inputTag.setAttribute('value','');
		inputAvgWeek.innerHTML = '0';
		inputAvgDay.innerHTML = '0';
		btnOptions.setAttribute('class','hd');
		btnRefresh.setAttribute('class','hd');
		btnSave.setAttribute('class','disabled');
				
		// copy node and update
		item = template.cloneNode(true);	  
		item.setAttribute('id','f');
		item.setAttribute('class','probe');

		
		probesList.appendChild(item);

		$("#f.probe > input#tag_input.tag").focus();
		
		

	}
}

// evaluate xpath
function xpath(path, node) {
  return document.evaluate(path, node).iterateNext();
}

function buildProbeQuery(probeObj){
	if(probeObj){
		if (probeObj.radius == undefined){
			return 'http://search.twitter.com/search?q=' + probeObj.query + '&ands=&phrase=&ors=&nots=&tag=&lang=all&from=&to=&ref=&near=&within=&units=km&since=&until=&rpp=15';
		}else{
			return 'http://search.twitter.com/search?q=' + probeObj.query + '&ands=&phrase=&ors=&nots=&tag=&lang=all&from=&to=&ref=&near=&within=' + probeObj.radius + '&units=km&since=&until=&rpp=15' + '&geocode=' + escape(probeObj.latitude + ',' + probeObj.longitude + ',' + probeObj.radius + 'km');
		}
	}else{
		return 'about:';
	}
}
function save() {

	
	$('#f').each(function(i){

		/*
		 * validate search term
		 */
		 var tagObj = $(' > input#tag_input.tag',this);

		 if (!tagObj.val()){
			 $(tagObj).addClass('warn');
			 /*
			  * TODO: add warning message
			  */
			 return false;
		 }

		var tagProbe = new Probe();
		tagProbe.query = tagObj.val();
		tagProbe.shortTermTweetsPerMin = 0;
		tagProbe.longTermTweetsPerMin = 0 ;

		chrome.extension.getBackgroundPage().showNoEvents();
		
		probeManager.setProbe(tagProbe);
		$(this).attr('id','f_' + tagProbe.id );

		$(this).addClass('loader');
		$(' > span#btnRefresh',this).addClass('reloading');

		
		
		port.postMessage({probeTagChanged: tagProbe});
		
	});

	//markClean();

	/*
	 * TODO: add communication with background.html
	 */
	 //console.log('TODO: add communication with background.html\n port.postMessage({probeTagAdded: tagProbe})');

	
	//chrome.extension.getBackgroundPage().init();
}

function refreshAll() {

	$('.probe > span#btnRefresh').removeClass('idle');
	$('.probe > span#btnRefresh').addClass('reloading');
	
	chrome.extension.getBackgroundPage().updateProbes(function(count) {
		console.log('updateProbes.callback:' + count);
	});

}	

function goToUrl(url) {
chrome.tabs.getAllInWindow(undefined, function(tabs) {
for (var i = 0, tab; tab = tabs[i]; i++) {
  if (tab.url && (tab.url == url)) {
    chrome.tabs.update(tab.id, {selected: true});
    return;
  }
}
chrome.tabs.create({url: url});
});
}	


function back(){
	$("div#options").slideUp("fast");
}

--></script>


<div id="header">
<!-- 
	<h1><script type="text/javascript">_writeMessage('default_title');</script></h1>
-->
	<div style="position:absolute; top:11px; right: 15px">
		<span class="link" onclick="refreshAll()"><script type="text/javascript">_writeMessage('popup_refresh');</script></span> | <span class="link" onclick="goToUrl('options.html');"><script type="text/javascript">_writeMessage('popup_options');</script></span> | <span class="link" onclick="window.close()"><script type="text/javascript">_writeMessage('popup_close');</script></span>
	</div>
</div>


<div id="config">

<ol id="template" class="probe">
	<li><span id="iconService"></span>
	<span id="tag" class="span_tag hd"><!--  --></span>
	<span id="probe_geo" class="span_geo hd"><!--  --></span>
	<input type="text" id="tag_input" class="tag" maxlength="30">
	<span class="avgWeek">0</span>
	<span class="avgDay">0</span>

	<span id="btnRefresh" class="idle"></span>
	<span id="btnSave"></span>
	<span id="btnRemove"></span>
	<span id="btnOptions"></span>	
	</li>
</ol>
<ol id="probes">
	<li class="title">
	<span class="tKeywords"><script type="text/javascript">_writeMessage('popup_keywords');</script></span>
	<span class="cTpM"><script type="text/javascript">_writeMessage('popup_cTpM');</script></span>
	<span class="ltTpM"><script type="text/javascript">_writeMessage('popup_ltTpM');</script></span>
	</li>
</ol>
</div>
<span class="cls"><!--  --></span>

<div id="footr">
<span id="btnAdd"> <script type="text/javascript">_writeMessage('button_addnew');</script></span>

<div class="option_row" style="padding-top:5px;">
	<div class="option_name"><script type="text/javascript">_writeMessage('popup_searchresults');</script></div>
	<div class="option_picker">
	<select id="open_results">
		<option value="open_in_current_window"><script type="text/javascript">_writeMessage('searchresults_currentwindow');</script></option>

<!--  <option value="open_in_new_window"><script type="text/javascript">_writeMessage('searchresults_newwindow');</script></option>  -->
	</select>
	<button id="show-button" onclick="openResults();" disabled="disabled"><script type="text/javascript">_writeMessage('button_show');</script></button>
	</div>
</div>
</div>

</body>
</html>